<template>
    <!-- 面板头部 -->
    <panelHead :route="route" />

    <!-- 添加和删除陪护师按钮 -->
    <div class="btns">
        <el-button :icon="Plus" type="primary" size="small" @click="open(null)">新增</el-button>
        <el-popconfirm confirm-button-text="是" cancel-button-text="否" cancel-button-type="info" :icon="InfoFilled"
            icon-color="#626AEF" title="是否确认删除选中的陪护师?" @confirm="confirmEvent" @cancel="cancelEvent">
            <template #reference>
                <el-button type="danger" size="small" :icon="Delete">删除</el-button>
            </template>
        </el-popconfirm>
    </div>

    <!-- 陪护师表格 element-plus -->
    <el-table :data="tableData.list" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="id" />
        <el-table-column prop="name" label="昵称" />
        <el-table-column prop="avatar" label="头像">
            <template #default="scope">
                <el-image :src="scope.row.avatar" style="width: 40px; height: 40px" alt="" />
            </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别">
            <template #default="scope">
                {{ scope.row.sex === 1 ? '男' : '女' }}
            </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" />
        <el-table-column prop="active" label="状态">
            <template #default="scope">
                <el-tag :type="scope.row.active ? 'success' : 'danger'">{{ scope.row.active ? '正常' : '异常' }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间">
            <template #default="scope">
                <div class="flex-box">
                    <el-icon>
                        <Clock />
                    </el-icon>
                    <span style="margin-left: 10px;">{{ scope.row.create_time }}</span>
                </div>
            </template>
        </el-table-column>
        <el-table-column label="操作">
            <template #default="scope">
                <!-- scope.row 表示当前行的数据对象 -->
                <el-button type="primary" @click="open(scope.row)">编辑</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-info">
        <el-pagination v-model:current-page="paginationData.pageNum" :page-size="paginationData.pageSize" size="small"
            :background="false" layout="total, prev, pager, next" :total="tableData.total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 添加陪护师弹窗 -->
    <el-dialog v-model="dialogFormVisible" :before-close="beforeClose" :title="dialogTitleText" width="500">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="auto" label-position="left">

            <el-form-item v-show="false" prop="id">
                <el-input v-model="form.id" />
            </el-form-item>

            <el-form-item label="昵称" prop="name">
                <el-input v-model="form.name" placeholder="请填写陪护师昵称" />
            </el-form-item>

            <el-form-item label="头像" prop="avatar">
                <el-button v-if="!form.avatar" type="primary" @click="dialogImgVisible = true">点击上传</el-button>
                <el-image v-else :src="form.avatar" style="width: 100px; height: 100px" alt="" />
            </el-form-item>

            <el-form-item label="性别" prop="sex">
                <el-select v-model="form.sex" placeholder="请选择性别">
                    <el-option label="男" value="1" />
                    <el-option label="女" value="2" />
                </el-select>
            </el-form-item>

            <el-form-item label="年龄" prop="age">
                <el-input-number v-model="form.age" :min="18" :max="50" />
            </el-form-item>

            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="form.mobile" placeholder="请填写手机号" />
            </el-form-item>

            <el-form-item label="是否生效" prop="active">
                <el-radio-group v-model="form.active">
                    <el-radio :value="0">失效</el-radio>
                    <el-radio :value="1">生效</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>

        <!-- 确认按钮 -->
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="confirm(formRef)">确认</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 添加陪护师选择头像弹窗 -->
    <el-dialog v-model="dialogImgVisible" title="选择图片" width="680">
        <div class="image-list">
            <!-- 遍历陪护师头像列表 点击头像时将当前选中的头像索引赋值给currentPhoto 并显示选中状态 -->
            <div v-for="(item, index) in photoListData" :key="item.name" class="img-box" @click="currentPhoto = index">
                <!-- 如果当前选中的头像索引与当前头像索引相同 则显示选中状态 -->
                <div class="select" v-if="currentPhoto === index">
                    <el-icon color="#fff">
                        <Check />
                    </el-icon>
                </div>
                <el-image :src="item.url" style="width: 148px; height: 148px" alt="" />
            </div>
        </div>
        <!-- 取消和确认按钮 -->
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogImgVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmPhoto">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup name="Staff">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { Plus, InfoFilled, Delete } from '@element-plus/icons-vue'
import { photoList, companionCreate, companionList, deleteCompanion } from '@/api'
import dayjs from 'dayjs'
import { useRoute } from 'vue-router'

const route = useRoute()

// 弹窗是否显示
const dialogFormVisible = ref(false)
// 弹窗选择头像
const dialogImgVisible = ref(false)
// 陪护师头像列表
const photoListData = ref([])
// 当前选中的头像
const currentPhoto = ref(0)
// 弹窗标题
const dialogTitleText = ref('')
// 选中的数据
const selectedTableData = ref([])

// 赋值选中的数据的id
const handleSelectionChange = (val) => {
    selectedTableData.value = val.map(item => ({ id: item.id }))
}

// 删除确认
const confirmEvent = () => {
    if (selectedTableData.value.length === 0) {
        return ElMessage.warning('请选择要删除的陪护师')
    }

    deleteCompanion({ id: selectedTableData.value }).then(({ data }) => {
        if (data.code === 10000) {
            ElMessage.success('删除陪护师成功')
            // 刷新陪护师列表
            getStaffList()
        } else {
            ElMessage.error(data.msg)
        }
    })
}

// 删除取消
const cancelEvent = () => {
    return
}

// 确认选择头像
const confirmPhoto = () => {
    // 将选中的头像赋值给form.avatar
    form.avatar = photoListData.value[currentPhoto.value].url
    // 关闭弹窗
    dialogImgVisible.value = false
}

// 关闭弹窗的回调
const beforeClose = () => {
    dialogFormVisible.value = false
    // 重置弹窗表单
    formRef.value.resetFields()
}

// 打开弹窗
const open = (rowData) => {
    dialogFormVisible.value = true
    // 弹窗打开时form生成是异步的
    nextTick(() => {
        if (rowData) {
            // 将rowData中的数据赋值给form
            Object.assign(form, rowData)
            // 设置弹窗标题
            dialogTitleText.value = '编辑陪护师'
        } else {
            // 设置弹窗标题
            dialogTitleText.value = '添加陪护师'
        }
    })
}
const formRef = ref(null)

const form = reactive({
    id: '',
    name: '',
    mobile: '',
    sex: '',
    age: 28,
    active: 1,
    avatar: '',
})

// 陪护师列表数据
const tableData = reactive({
    list: [],
    total: 0
})

onMounted(() => {
    // 获取陪护师头像
    photoList().then(({ data }) => {
        photoListData.value = data.data
    })
    // 获取陪护师列表
    getStaffList()
})

// 分页数据
const paginationData = reactive({
    pageNum: 1, // 当前页码
    pageSize: 10 // 每页条数
})

// 分页条数改变
const handleSizeChange = (size) => {
    paginationData.pageSize = size
    getStaffList()
}

// 分页页码改变
const handleCurrentChange = (pageNum) => {
    paginationData.pageNum = pageNum
    getStaffList()
}

// 获取陪护师列表
const getStaffList = () => {
    companionList(paginationData).then(({ data }) => {
        console.log(data)
        // 将获取到的数据赋值给tableData
        const { list, total } = data.data
        // 将时间戳转换为日期格式
        list.forEach(item => {
            item.create_time = dayjs(item.create_time).format('YYYY-MM-DD')
        })
        tableData.list = list
        tableData.total = total
    })
}

// 弹窗表单验证  trigger: 'blur' 失去焦点时触发
const rules = reactive({
    // required: true 必填 message: 提示信息
    name: [{ required: true, trigger: 'blur', message: '请输入权限名称' }],
    avatar: [{ required: true, message: '请选择头像' }],
    sex: [{ required: true, trigger: 'change', message: '请选择性别' }],
    mobile: [{ required: true, trigger: 'blur', message: '请输入手机号' }]
})
// 确认按钮 弹窗表单提交校验 element-plus
const confirm = async (formEl) => {
    if (!formEl) return
    // 手动触发弹窗表单验证
    await formEl.validate((valid, fields) => {
        if (valid) {
            companionCreate(form).then(({ data }) => {
                if (data.code === 10000) {
                    ElMessage.success('陪护师' + (form.id ? '修改' : '添加') + '成功')
                    // 关闭弹窗重置表单
                    beforeClose()
                    // 刷新陪护师列表
                    getStaffList()
                } else {
                    ElMessage.error(data.msg)
                }
            })
        } else {
            console.log('error submit!!', fields)
        }
    })
}
</script>

<style lang="less" scoped>
.btns {
    padding: 10px 0 10px 10px;
    background-color: #fff;
}

.image-list {
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    .img-box {
        position: relative;

        .select {
            position: absolute;
            left: 0px;
            top: 0px;
            width: 24px;
            height: 24px;
            background-color: #67c23a;
            z-index: 999;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }

    .el-image {
        margin-right: 10px;
        margin-bottom: 10px;
    }
}
</style>